<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="轮播图(690*345)"
        >
          <a-upload
            :action="this.$baseURL+'/common/upload/uploadImg'"
            listType="picture-card"
            :fileList="fileList"
            @preview="uploadPreview"
            @change="uploadChange"
            :disabled="flag"
          >
            <div v-if="fileList.length < 3">
              <a-icon type="plus"/>
              <div class="ant-upload-text">上传轮播图</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
            <img alt="example" style="width: 100%" :src="previewImage"/>
          </a-modal>
        </a-form-item>


        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="轮播图信息配置"
        >
          <div v-for="(item,i) in items">
            <a-select style="width: 50%" v-model="item.id">
              <a-select-option v-for="itemp1 in typeList" :key="itemp1.id">{{itemp1.name}}</a-select-option>
            </a-select>
            &nbsp;
            <a-input style="width: 45%" placeholder="商品id或者url" v-model="item.transUrl"/>
          </div>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="背景图(690*340)"
        >
          <a-upload
            :action="this.$baseURL+'/common/upload/uploadImg'"
            listType="picture-card"
            :fileList="backList"
            @preview="uploadPreviewBack"
            @change="uploadChangeBack"
            :beforeUpload="beforeUpload"
            :data="ruleForm"
          >
            <div v-if="backList.length < 1">
              <a-icon type="plus"/>
              <div class="ant-upload-text">上传背景图</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
            <img alt="example" style="width: 100%" :src="previewImage"/>
          </a-modal>
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { addFileConfig, deletePic,selectByMasterIdOrType } from '@/api/companyService/company'
  import pick from 'lodash.pick'

  export default {
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),
        businessServiceList: [],
        defaultBusinessService: [],
        businessService: {},
        fileList: [],
        isDisabled: false,
        previewVisible: false,
        previewImage: '',
        fileList: [],
        backList: [],
        flag: false,
        items: [],
        ruleForm: {
          height: 690,
          width: 340
        },
        typeList: [{ id: 1, name: '内部跳转', value: 'inside' }, { id: 2, name: '网页跳转', value: 'page' }, {
          id: 3,
          name: '小程序跳转',
          value: 'skip'
        }],
        params: {}
      }
    },
    //--############  data() ###############-->

    created() {

    },

    //--############  methods() ###############-->
    methods: {
      add() {
        this.isDisabled = false
        this.visible = true
      },
      edit(record) {
        const _this = this
        this.isDisabled = true
        this.mdl = Object.assign({}, record)
        this.visible = true
        let queryParam = {}
        queryParam.masterId = this.mdl.id
        queryParam.type = 1
        selectByMasterIdOrType(queryParam).then(res => {
          this.fileList = res.result
          if(this.fileList.length>0){
            for (let i = 0; i < this.fileList.length ; i++) {
              let itemData = {
                id:this.fileList[i].transUrlType,
                transUrl:this.fileList[i].transUrl,
                index:this.fileList[i].uid
              }
              // this.items[i] = itemData;
              this.items.push(itemData)
            }
          }
        })
        let queryParamBack = {}
        queryParamBack.masterId = _this.mdl.id
        queryParamBack.type = 2
        selectByMasterIdOrType(queryParamBack).then(res => {
          _this.backList = res.result
        })

      },
      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl = {}
        this.items = []
      },
      handleOk() {
        const _this = this
        this.params = {}
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            _this.confirmLoading = true
            _this.confirmLoading = false
            let paramList = []
            for (let i = 0; i < _this.fileList.length; i++) {
              let fileUid = this.fileList[i].uid
              let fileItem = this.fileList[i]

              let item = _this.items[i]
              let itemUid = _this.items[i].index
              if (fileUid == itemUid) {
                fileItem.type = 1
                fileItem.masterId = _this.mdl.id
                fileItem.transUrl = item.transUrl
                fileItem.transUrlType = item.id
                paramList.push(fileItem)
              }
            }

            _this.backList.forEach(item => {
              item.type = 2
              item.masterId = _this.mdl.id
              paramList.push(item)
            })
            _this.params.fileManagementList = paramList
            values.fileManagementList = _this.params.fileManagementList
            values.masterId = _this.mdl.id
            console.log("addFileConfig---",values);
            addFileConfig(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('保存成功')
                _this.$emit('ok')
                _this.close()
              } else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })
      },
      handleCancel() {
        this.close()
      },
      uploadCancel() {
        this.previewVisible = false
      },
      uploadPreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadPreviewBack(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        this.fileList = info.fileList
        if (info.file.status === 'done') {

          /*动态添加配置详细信息*/
          let cope = {
            id: '',
            transUrl: '',
            index: info.file.response.uid
          }
          this.items.push(cope)
          this.fileList.pop()
          this.fileList.push(info.file.response)
          this.$message.success(`${info.file.name} 上传成功`)
          this.flag = false
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          let index = this.items.findIndex(item => {
            if (item.index == info.file.uid) {
              return true
            }
          })
          this.items.splice(index,1)
          deletePic(info.file.name).then(res => {
          })
        }
      },
      uploadChangeBack(info) {
        this.backList = info.fileList
        if (info.file.status === 'done') {
          this.backList.pop()
          if (info.file.response.uid == null) {
            this.$message.error(`图片宽高必须是690*340`)
            return
          }
          this.backList.push(info.file.response)
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          deletePic(info.file.name).then(res => {

          })
        }
      },
      beforeUpload(file) {
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isPNG = file.type === 'image/png'
        if (!isJPG && !isJPEG && !isPNG) {
          this.$message.error('只支持文件格式jpg,png')
        }
        return file.type
      }
    }
    //--############  methods() ###############-->
  }
</script>

<style scoped>

</style>
